require "prefabutil"

local assets =
{
    Asset("ANIM", "anim/bboy_nether_moth.zip"),
}

local prefabs =
{
    "bboy_nether_mothwings",
    "butter",
    "planted_bboy_nether_blossom",
}

local brain = require "brains/butterflybrain"

local HEALTH_DRAIN_INTERVAL = 25 -- 每隔 25 秒执行一次
local HEALTH_DRAIN_RADIUS = 3    -- 影响半径（可按需调整）

local function DrainNearbyPlayers(inst)
    if not inst:IsValid() then return end
    local x, y, z = inst.Transform:GetWorldPosition()
    local players = FindPlayersInRange(x, y, z, HEALTH_DRAIN_RADIUS, true)
    for _, p in ipairs(players) do
        if p.components ~= nil and p.components.health ~= nil and not p.components.health:IsDead() then
            -- 第三个参数作为伤害来源标记，方便战斗日志/死亡提示
            p.components.health:DoDelta(-1, false, inst.prefab)
        end
    end
end

local function OnDropped(inst)
    inst.sg:GoToState("idle")
    if inst.butterflyspawner ~= nil then
        inst.butterflyspawner:StartTracking(inst)
    end
    if inst.components.workable ~= nil then
        inst.components.workable:SetWorkLeft(1)
    end
    if inst.components.stackable ~= nil then
        while inst.components.stackable:StackSize() > 1 do
            local item = inst.components.stackable:Get()
            if item ~= nil then
                if item.components.inventoryitem ~= nil then
                    item.components.inventoryitem:OnDropped()
                end
                item.Physics:Teleport(inst.Transform:GetWorldPosition())
            end
        end
    end
end

local function OnPickedUp(inst)
    if inst.butterflyspawner ~= nil then
        inst.butterflyspawner:StopTracking(inst)
    end
end

local function OnWorked(inst, worker)
    if worker.components.inventory ~= nil then
        if inst.butterflyspawner ~= nil then
            inst.butterflyspawner:StopTracking(inst)
        end
        worker.components.inventory:GiveItem(inst, nil, inst:GetPosition())
        worker.SoundEmitter:PlaySound("dontstarve/common/butterfly_trap")
    end
end

local function OnDeploy(inst, pt, deployer)
    local flower = SpawnPrefab("planted_bboy_nether_blossom")
    if flower then
        flower.Transform:SetPosition(pt:Get())
        inst.components.stackable:Get():Remove()
        if deployer and deployer.SoundEmitter then
            deployer.SoundEmitter:PlaySound("dontstarve/common/plant")
        end
    end
end

local function fn()
    local inst = CreateEntity()

    -- 核心组件
    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddDynamicShadow()
    inst.entity:AddSoundEmitter()
    inst.entity:AddNetwork()

    -- 初始化物理
    MakeTinyFlyingCharacterPhysics(inst, 1, .5)

    inst:AddTag("butterfly")
    inst:AddTag("flying")
    inst:AddTag("ignorewalkableplatformdrowning")
    inst:AddTag("insect")
    inst:AddTag("smallcreature")
    inst:AddTag("cattoyairborne")
    inst:AddTag("wildfireprotected")
    inst:AddTag("deployedplant")
    inst:AddTag("noember")
    inst:AddTag("bboy_nether_moth")

    inst:AddTag("pollinator")

    inst.Transform:SetTwoFaced()

    inst.AnimState:SetBuild("bboy_nether_moth")
    inst.AnimState:SetBank("bboy_nether_moth")
    inst.AnimState:PlayAnimation("idle")
    inst.AnimState:SetRayTestOnBB(true)

    inst.DynamicShadow:SetSize(.8, .5)

    MakeInventoryFloatable(inst)

    MakeFeedableSmallLivestockPristine(inst) -- 貌似是可以喂养
    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    ---------------------
    inst:AddComponent("locomotor") -- locomotor 必须在 stategraph 之前构建
    inst.components.locomotor:EnableGroundSpeedMultiplier(false)
    inst.components.locomotor:SetTriggersCreep(false)

    inst:SetStateGraph("SGbutterfly")
    inst.sg.mem.burn_on_electrocute = true

    ---------------------
    inst:AddComponent("stackable")
    inst:AddComponent("inventoryitem")
    inst.components.inventoryitem.canbepickedup = false
    inst.components.inventoryitem.canbepickedupalive = true
    inst.components.inventoryitem.nobounce = true
    inst.components.inventoryitem.pushlandedevents = false

    ------------------
    inst:AddComponent("pollinator") -- 授粉组件

    ------------------
    inst:AddComponent("health")
    inst.components.health:SetMaxHealth(1)

    ------------------
    inst:AddComponent("combat")
    inst.components.combat.hiteffectsymbol = "butterfly_body" -- 命中效果符号

    ------------------
    inst:AddComponent("knownlocations")

    MakeSmallBurnableCharacter(inst, "butterfly_body")
    MakeTinyFreezableCharacter(inst, "butterfly_body")

    ------------------
    inst:AddComponent("inspectable")

    -- 升san光环
    inst:AddComponent("sanityaura")
    inst.components.sanityaura.aura = TUNING.SANITYAURA_TINY

    ------------------
    inst:AddComponent("lootdropper")
    inst.components.lootdropper:AddRandomLoot("butter", 0.1)
    inst.components.lootdropper:AddRandomLoot("bboy_nether_mothwings", 5)
    inst.components.lootdropper.numrandomloot = 1

    ------------------
    inst:AddComponent("workable")
    inst.components.workable:SetWorkAction(ACTIONS.NET)
    inst.components.workable:SetWorkLeft(1)
    inst.components.workable:SetOnFinishCallback(OnWorked)

    ------------------
    inst:AddComponent("tradable")

    ------------------
    inst:AddComponent("deployable")
    inst.components.deployable.ondeploy = OnDeploy
    inst.components.deployable:SetDeployMode(DEPLOYMODE.PLANT)
    inst.components.deployable:SetDeploySpacing(DEPLOYSPACING.LESS)

    MakeHauntablePanicAndIgnite(inst)

    -- 每 25 秒对范围内玩家造成 1 点生命值损失
    if inst._healthdrain_task ~= nil then
        inst._healthdrain_task:Cancel()
    end
    inst._healthdrain_task = inst:DoPeriodicTask(HEALTH_DRAIN_INTERVAL, DrainNearbyPlayers)

    inst:SetBrain(brain)

    inst.butterflyspawner = TheWorld.components.butterflyspawner
    if inst.butterflyspawner ~= nil then
        inst.components.inventoryitem:SetOnPutInInventoryFn(inst.butterflyspawner.StopTrackingFn)
        inst:ListenForEvent("onremove", inst.butterflyspawner.StopTrackingFn)
        inst.butterflyspawner:StartTracking(inst)
    end

    MakeFeedableSmallLivestock(inst, TUNING.BUTTERFLY_PERISH_TIME, OnPickedUp, OnDropped)

    inst:ListenForEvent("onremove", function()
        if inst._healthdrain_task ~= nil then
            inst._healthdrain_task:Cancel()
            inst._healthdrain_task = nil
        end
    end)

    return inst
end

return Prefab("bboy_nether_moth", fn, assets, prefabs),
    MakePlacer("bboy_nether_moth_placer", "bboy_nether_blossom", "bboy_nether_blossom", "f1")
